import re
#import logging

class DBInput():

    __cursor      = None
    __last_query  = None
    __logger      = None
    __var_pattern = re.compile(":(\w+)")
    
    def __init__(self, config, cursor ):
        "Sets the DB parameters"
        self.__logger = config.logger
        self.__cursor = cursor
        self.__db_type= config.database_type


    def __getDict(self, query, bind_vars=[], nkeys=1):
        "returns results of a query as a dictionary with first n values as the key"
        self.__runQuery(query, bind_vars)
        result = {}
        try:
            row = self.__cursor.fetchone()

            while row:
                key = row[:nkeys]
                val = row[nkeys:]
                key = len(key) == 1 and key[0] or key
                val = len(val) == 1 and val[0] or val
                result[key] = val
                row = self.__cursor.fetchone()
        except Exception, info:
            self.__logger.debug("No rows returned")

        return result


    def __runQuery(self, query, bind_vars):
        "run query on database using bind variables"
       
        self.__last_query = "%s %s" % (query, bind_vars) # display it on error
        #self.__logger.debug("Executing query: %s" % self.__last_query.strip())
        try:
            if bind_vars:
                self.__cursor.execute(query, bind_vars)
            else:
                self.__cursor.execute(query)
            self.__last_query = None # clear if no exception
        except Exception, info:
            self.__logger.debug("Generic - RunQuery - Error executing last query: %s" % info)
    
    def getTestResult(self,command):
        """returns command response in the form of dictionary"""
        test_result = self.__getDict(command)
        return test_result
